package com.ruoyi.media.mediaLogin.service.impl;

import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.media.forestApi.common.WechatMiniProRequest;
import com.ruoyi.media.forestApi.vo.BaseResVo;
import com.ruoyi.media.mediaLogin.service.IMediaLoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 自媒体平台配置Service业务层处理
 *
 * @author dqw
 * @date 2023-03-23
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class MediaLoginServiceImpl implements IMediaLoginService {

    /**
     * 微信小程序token键
     */
    public static String wxTokenKey = "wx_access_token";
    /**
     * 微信小程序请求方法
     */
    private final WechatMiniProRequest wechatMiniProRequest;




    /**
     * 获取微信小程序accessToken
     * @return
     */
    @Override
    public String getWxMiniAccessToken() {
        String accessToken = "";
        try{
            Object token =  RedisUtils.getCacheObject(wxTokenKey);
            if(token == null){
                BaseResVo accessTokenVo = wechatMiniProRequest.getAccessToken();
                RedisUtils.setCacheObject(wxTokenKey,accessTokenVo.getAccess_token(),
                    Duration.ofSeconds(accessTokenVo.getExpires_in() - 120));  //添加键值对并设置提前两分钟失效
                accessToken = accessTokenVo.getAccess_token();
            }else{
                accessToken = token.toString();
            }
        }catch (Exception e){
            log.info(e.getMessage());
        }
        return accessToken;
    }


    /**
     * 生成小程序二维码时将参数存入redis
     * @param ticket
     */
    @Override
    public void setTicketByRedis(String ticket) {
        Map<String,Object> statusMap = new HashMap<>();
        statusMap.put("status",0);  //未扫码状态
        statusMap.put("dataMap",null);
        RedisUtils.setCacheObject(ticket,statusMap,Duration.ofMinutes(10));
    }





}
